package com.hzh.page.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzh.page.dao.AuthenticationRoleMapper;
import com.hzh.page.pojo.AuthenticationMenuEntity;
import com.hzh.page.pojo.AuthenticationRoleEntity;
import com.hzh.page.pojo.AuthenticationRoleMenuEntity;
import com.hzh.page.pojo.AuthenticationUserRoleEntity;
import com.hzh.page.service.AuthenticationMenuService;
import com.hzh.page.service.AuthenticationRoleMenuService;
import com.hzh.page.service.AuthenticationRoleService;
import com.hzh.page.service.AuthenticationUserRoleService;
import com.hzh.page.vo.AuthenticationRoleMenuVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口
 *
 * @author hzh
 * @date 2022-11-02
 */
@Slf4j
@Service("AuthenticationRoleService")
public class AuthenticationRoleServiceImpl extends ServiceImpl<AuthenticationRoleMapper, AuthenticationRoleEntity> implements AuthenticationRoleService {

    @Resource
    private AuthenticationRoleMenuService roleMenuService;

    @Resource
    private AuthenticationUserRoleService userRoleService;

    @Resource
    private AuthenticationMenuService menuService;

    @Override
    public AuthenticationRoleMenuVO getRoleMenuByRoleId(Integer roleId) {
        AuthenticationRoleMenuVO roleMenuVO = new AuthenticationRoleMenuVO();
        AuthenticationRoleEntity roleEntity = baseMapper.selectById(roleId);
        if (roleEntity != null) {
            BeanUtils.copyProperties(roleEntity, roleMenuVO);
            List<AuthenticationRoleMenuEntity> roleMenuEntities = roleMenuService.list(new QueryWrapper<AuthenticationRoleMenuEntity>().eq("role_id", roleEntity.getId()));
            if (roleMenuEntities.size() == 0 || roleMenuEntities.isEmpty()) {
                return roleMenuVO;
            }
            List<Integer> menuIds = roleMenuEntities.stream().map(AuthenticationRoleMenuEntity::getMenuId).collect(Collectors.toList());
            List<AuthenticationMenuEntity> menuEntities = menuService.listByIds(menuIds);
            List<String> rights = menuEntities.stream().map(AuthenticationMenuEntity::getRouteKey).collect(Collectors.toList());
            roleMenuVO.setRights(rights);
            return roleMenuVO;
        } else {
            return null;
        }
    }

    @Override
    public AuthenticationRoleEntity getRoleByUserId(Integer userId) {
        AuthenticationUserRoleEntity userRoleEntity = userRoleService.getOne(new QueryWrapper<AuthenticationUserRoleEntity>().eq("user_id", userId));
        AuthenticationRoleEntity roleEntity = baseMapper.selectById(userRoleEntity.getRoleId());
        return roleEntity;
    }
}
